package com.scalar.chiptrack.adaptor.akrossilicon.unisem;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;

import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import java.util.Date;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 19 Mar, 2010
 * Time: 12:27:31 PM
 */
public class UNISEMPOP3Adaptor extends JobHandler implements AdaptorConstants
{
    private static final String HOST               = "mail.scalarsoft.com";

    public static final String FILE_NAME_ASSY_WIP 	   = "GENERAL_WIP_ASSYWIP";
    public static final String FILE_NAME_FT_WIP 	   = "GENERAL_WIP_TESTWIP";

    public static final String ADAPTOR_NAME        = "UNISEM_WIP";

    private static final String SUBJECT_WIP        = "A081 ASSEMBLY WIP Report";
    private static final String SUBJECT_FT_WIP     = "A081 TEST WIP Report";

    private Logger m_adaptorLogger      = null;
    private String m_dataOutputDir      = null;
    private String m_username           = null;
    private String m_password           = null;
    private int    m_adaptor_id         = -1;

    public UNISEMPOP3Adaptor() throws Exception
    {
        try
        {
            VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation( VENDOR_NAME_UNISEM, LOCATION_TYPE_ASSEMBLY);

            m_username = vendorAdaptor.getUserId().trim();
            m_password = vendorAdaptor.getPassWord().trim();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory().trim();

            if (m_dataOutputDir != null)
            {
                if (m_dataOutputDir.endsWith("/") || m_dataOutputDir.endsWith("\\"))
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }
                AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
                m_adaptorLogger = AdaptorUtils.getAdaptorLogger( m_dataOutputDir, VENDOR_NAME_UNISEM );
                AdaptorUtils.setLogger( m_adaptorLogger );
            }
        }
        catch (Exception se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading UNISEM Adaptor Username, Password details from database, Exception: " + se);
            throw se;
        }
    }

    //Main Method
    public static void main(String[] args) throws Exception
    {
        new UNISEMPOP3Adaptor().execute();
    }

    /**
     *
     * @throws Exception
     */
    public void execute() throws Exception
    {
        try
        {
            m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);
            // Step 1
             // prints the version of Adaptor
            AdaptorUtils.printHeader( VENDOR_NAME_UNISEM, CONSTANT_ADAPTOR );

            // Step 2
            // removes the old files out side done directory
            AdaptorUtils.removeOldFiles(m_dataOutputDir, m_adaptorLogger);
            // Step 3
            //Retrive All the Messages
            Message[] messages = AdaptorUtils.getAllPOP3InboxMessages( HOST, m_username, m_password);
            // Step 4
            // Retrieve & Saves the latest message
            Message assyWipMessage = AdaptorUtils.readLatestMessage( messages, SUBJECT_WIP );

            // To process the Message and download the files
            if ( assyWipMessage != null )
            {
                downLoadMessage( m_adaptor_id, assyWipMessage, assyWipMessage.getSentDate(), SUBJECT_WIP, m_dataOutputDir, FILE_EXTN_XLS, null );
                assyWipMessage = null;
            }
            else
            {
                 log("\n\n****The Requested Subject was not found in INBOX***" + SUBJECT_WIP + "\n");
                 System.out.println("\n\n****The Requested Subject was not found in INBOX***" + SUBJECT_WIP+"\n" );
            }

            Message ftWipMessage = AdaptorUtils.readLatestMessage( messages, SUBJECT_FT_WIP );

            // To process the Message and download the files
            if ( ftWipMessage != null )
            {
                downLoadMessage( m_adaptor_id, ftWipMessage, ftWipMessage.getSentDate(), SUBJECT_FT_WIP, m_dataOutputDir, FILE_EXTN_XLS, null );
                ftWipMessage = null;
            }
            else
            {
                 log("\n\n****The Requested Subject was not found in INBOX***" + SUBJECT_FT_WIP + "\n");
                 System.out.println("\n\n****The Requested Subject was not found in INBOX***" + SUBJECT_FT_WIP+"\n" );
            }
        }
        catch (Exception e)
        {
            AdaptorUtils.removeOldFiles(m_dataOutputDir, m_adaptorLogger);
            AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id);
            System.out.println("Exception while trying to connect and read data from " + HOST +" site: " + e);
            log("Exception while trying to connect and read data from " + HOST +" site: " + e);
            e.printStackTrace();
            throw e;
        }
    }

    private void downLoadMessage( int m_adaptor_id , Message message, Date sentDate, String subject , String outputDir, String fileType, String appendFileName) throws Exception
    {
        if ( message == null )
        {
            return;
        }

        Multipart mp        = null;
        Part part           = null;
        String disposition  = null;
        InputStream inputStream = null;

        String fileName     = null;
        String fileExtn    = null;
        log("Processing  Message for "+ subject + " .......");
        System.out.println("Processing  Message for "+ subject + " .......");

        try
        {
            Object obj = message.getContent();

            if (obj instanceof Multipart )
            {
                mp = (Multipart) obj;

                for ( int i = 0; i < mp.getCount(); i++ )
                {
                    part = mp.getBodyPart(i);

                    //disposition = part.getDisposition();

                    //taking the wip & ASSEMBLY attachmentS
                    //if ( ( disposition != null ) && ( disposition.equals( Part.ATTACHMENT ) || disposition.equals( Part.INLINE ))  )
                    //{
                        if ( part.getFileName() != null && part.getFileName().toUpperCase().indexOf("PDF") < 1 )
                        {
                            fileName =  part.getFileName().substring( 0 , part.getFileName().lastIndexOf(".") );
                            fileExtn  = part.getFileName().substring( part.getFileName().lastIndexOf(".") + 1 , part.getFileName().length() );

                            inputStream = part.getInputStream();

                            if ( fileName != null )
                            {
                                fileName = fileName.replaceAll("-", "_").toUpperCase();

                                if ( m_adaptor_id > 0 )
                                {
                                    AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , fileName, fileExtn, StringUtils.formatDateToString( sentDate, "MM/dd/yyyy HH:mm:ss") ) ;
                                }

                                if ( appendFileName != null )
                                {
                                    fileName = appendFileName +"_" + fileName;
                                }

                                log("\tDownloding "+subject+"................. ");
                                System.out.println("\tDownloding "+subject+"................. ");

                                AdaptorUtils.saveAsBinaryFile( new BufferedInputStream(inputStream), outputDir, fileName, fileExtn, true /* append time stamp */);
                                fileName = null;
                                System.out.println("Done.\n"  );
                            }
                        }
                    //}
                } //FOR LOOP
            }//IF FOR CHECKING ONLY MULTI PART

        }
        catch( Exception e)
        {
            System.out.println("EXception Occcuered while Proceess and downloading the Messge:" + e );
            e.printStackTrace();
            throw e;
        }
        finally
        {
            if ( inputStream != null )
            {
                try
                {
                    inputStream.close();
                    inputStream = null;
                }
                catch (IOException e)
                {
                }
            }
        }
    }
    /**
     *
     * @param message
     */
    private void log(String message)
    {

        if (message == null) return;

        if (m_adaptorLogger != null)
        {
            synchronized (m_adaptorLogger)
            {
                m_adaptorLogger.logDebug(message + LINE_SEPARATOR);
            }
        }
        else
        {
            System.out.println(message);
        }
    }
}
